'use strict';
module.exports = {
	/**
	 * XXXnameXXX
	 * @url client/pay/kh/PayPal 前端调用的url参数地址
	 * data 请求参数
	 * @param {String} params1  参数1
	 */
	main: async (event) => {
		let { data = {}, userInfo, util, filterResponse, originalParam } = event;
		let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
		let { uid, orderInfo } = data;
		let res = { code: 0, msg: "" };
		// 业务逻辑开始-----------------------------------------------------------

		let user_id = orderInfo.user_id;
		let _add_time = new Date().getTime();
		let _add_time_str = vk.pubfn.timeFormat(new Date(), "yyyy-MM-dd hh:mm:ss");

		//修改订单状态，并给用户加金豆余额
		const update_order = await db.collection('a_recharge').where({
			out_trade_no: orderInfo.out_trade_no
		}).update({
			shifu_amount: orderInfo.recharge_amount,
			pay_status: 1,
			_add_time: _add_time,
			_add_time_str: _add_time_str
		})

		if (orderInfo.subject == "充值金豆") {
			//如果修改成功，给用户增加金豆数量
			//此方法腾讯云和阿里云都支持
			let newInfo = await vk.baseDao.updateAndReturn({
				dbName: "uni-id-users",
				whereJson: {
					_id: user_id
				},
				dataJson: {
					had_youhui: true, //had_youhui可以判断用户是否付费过，便于付费用户数量统计
					balance: _.inc(orderInfo.bean)
				}
			});

			//添加金豆收支明细
			const add_jindou = await db.collection('a_jindou_detail').add({
				user_id: user_id,
				nickname: newInfo.nickname || "未绑定",
				change_num: orderInfo.bean, //增加的金豆数量
				changed_num: newInfo.balance, //支付后金豆余额
				change_reason: "支付" + orderInfo.recharge_amount + "分钱充值" + orderInfo.bean + "金豆",
				type: "income", //类型：expend:支出,income:收入。
				appid: newInfo.appid || "",
				appname: newInfo.appname || "",
				_add_time: _add_time,
				_add_time_str: _add_time_str
			})
			res.tips = "success";
		} else {
			let addtime = 0;
			//【开通会员】这个类型是为了兼容老版本的年费会员
			if (orderInfo.subject == "开通会员") {
				addtime = 31536000000 //365天
			}
			if (orderInfo.subject == "年度会员") {
				addtime = 31536000000 //365天
			}
			if (orderInfo.subject == "季度会员") {
				addtime = 7776000000 //90天
			}
			if (orderInfo.subject == "月度会员") {
				addtime = 2592000000 //30天
			}
			//先查询用户信息，是否已是会员
			let getres = await db.collection('uni-id-users').doc(user_id).field({
				plus_expire_time: true
			}).get()

			var nowtime = new Date().getTime();
			const plus_expire = getres.data[0].plus_expire_time
			if (plus_expire * 1 < nowtime * 1) {
				let new_expire_time = nowtime * 1 + addtime;
				//如果会员已到期，会员时间就是当前时间+addtime
				let updateVip = await db.collection('uni-id-users').doc(user_id).update({
					plus_type: 1,
					plus_expire_time: new_expire_time
				})
			} else {
				console.log("修改用户会员到期时间");
				let new_expire_time2 = plus_expire * 1 + addtime
				//如果会员没有到期，会员时间就是到期时间+addtime
				let updateVip2 = await db.collection('uni-id-users').doc(user_id).update({
					plus_expire_time: new_expire_time2
				})
			}
			res.tips = "success";
		}

		// 业务逻辑结束-----------------------------------------------------------
		return res;
	}
}
